package Servlet;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import com.oreilly.servlet.MultipartRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.UserModel;
import java.io.*;
import java.sql.Connection;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import model.RegisterModel;


/**
 *
 * @author acer
 */
@WebServlet(name="Register", urlPatterns={"/Register"})
public class Register extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    String post_user="",post_pass="",post_confirm_pass="",post_email="",post_full_name="",post_birthday="",post_gender="",post_about="",filename="";
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException,IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Connection con = null;
        Statement stmt = null;
        try {
            //System.out.println("hello:"+request.getParameter("username"));
            Class.forName("com.mysql.jdbc.Driver");
              con =DriverManager.getConnection("jdbc:mysql://localhost/progin_171_13509047?user=progin&password=progin");
              stmt = con.createStatement();
            String savedir=this.getServletContext().getRealPath("avatar");
            savedir.replace('\\', '/');
            MultipartRequest multireq;
            multireq = new MultipartRequest(request, savedir);
            filename = multireq.getFilesystemName("avatar");
//            System.out.println(multireq.getFilesystemName("avatar"));
            if(multireq.getParameter("username")!=null)
                post_user = multireq.getParameter("username");
            if(multireq.getParameter("password")!=null)
                post_pass = multireq.getParameter("password");
            if(multireq.getParameter("confirm_password")!=null)
                post_confirm_pass = multireq.getParameter("confirm_password");
            if(multireq.getParameter("email")!=null)
                post_email = multireq.getParameter("email");
            if(multireq.getParameter("real_name")!=null)
                post_full_name = multireq.getParameter("real_name");
            if(multireq.getParameter("birthday")!=null)
                post_birthday = multireq.getParameter("birthday");
            if(multireq.getParameter("sex")!=null)
                post_gender = multireq.getParameter("sex");
            if(multireq.getParameter("about")!=null)
                post_about = multireq.getParameter("about");

            String errmsg = validateAll(con);
            if(errmsg.isEmpty())
            {

                String newfilename =savedir+"\\"+post_user+".jpg";
                File anotherfile = multireq.getFile("avatar");
                //FileInputStream is = new FileInputStream(anotherfile);
                BufferedReader in = new BufferedReader(new FileReader(anotherfile));

                BufferedImage buffimg = ImageIO.read(anotherfile);
                ImageIO.write(buffimg, "jpg", new File(newfilename));

                RegisterModel r_model = new RegisterModel(con);
                r_model.insertRegistration(post_user, post_pass, post_confirm_pass, post_email, post_full_name, post_birthday, post_gender, post_about,newfilename);
                
            }
            else
            {
                StringBuilder err_builder = new StringBuilder();
                err_builder.append("err_msg=");
                err_builder.append(errmsg);
                StringBuilder other = new StringBuilder();
                other.append((post_user.isEmpty())?"":"&&username="+post_user);
                other.append((post_full_name.isEmpty())?"":"&&real_name="+post_full_name);
                other.append((post_email.isEmpty())?"":"&&email="+post_email);
                other.append((post_about.isEmpty())?"":"&&about="+post_about);
                response.sendRedirect("register.jsp?"+err_builder.toString()+other.toString());
            }
//            {
//
//            }
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Register</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Register at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        } catch (Exception ex)
        {System.out.println(ex.getMessage());ex.printStackTrace();}finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String validateAll(Connection connect) throws SQLException
    {
        StringBuilder errmsg= new StringBuilder();
        UserModel u_model =new UserModel(connect);
        if(post_user.length()<5)
            errmsg.append(1);
        if(post_pass.length()<8)
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(2);
        }
        if(post_user.equals(post_pass))
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(3);
        }
        if(post_email.equals(post_pass))
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(4);
        }
        if(!post_confirm_pass.equals(post_pass))
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(5);
        }
        if(!post_full_name.matches("\\S+ \\S+"))//cek nama
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(6);
        }
        if(!post_birthday.matches("\\d{4}-\\d{2}-\\d{2}"))//cek ultah
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(7);
        }
        if(!post_email.matches("\\S+@\\S+\\.\\S+\\S+"))//cek email
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(8);
        }
        if(!filename.matches("\\S+\\.((jpg)|(gif))"))//cek avatartype
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(9);
        }{
            
        }
        if(post_gender.equals("select_gender"))
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(10);
        }
        if(u_model.getUsername(post_user).getRow() !=0)
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(12);
        }
        if(u_model.getEmail(post_email).getRow() !=0)
        {
            if(!errmsg.toString().isEmpty())
                errmsg.append('|');
            errmsg.append(13);
        }
        return errmsg.toString();
    }
}
